package com.pxmeta.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pxmeta.user.entity.UserMatch;
import com.pxmeta.user.mapper.UserMatchMapper;
import com.pxmeta.user.service.IUserMatchService;
import org.springframework.stereotype.Service;

@Service
public class UserMatchServiceImpl extends ServiceImpl<UserMatchMapper, UserMatch> implements IUserMatchService {
    @Override
    public boolean like(Long userId, Long targetUserId) {
        UserMatch matchUser = getMatchUser(userId, targetUserId);
        if (matchUser == null){
            matchUser = new UserMatch();
            matchUser.setIsLike(1);
            matchUser.setMatchUserId(targetUserId);
            matchUser.setUserId(userId);
            this.save(matchUser);
        }else {
            matchUser.setIsLike(1);
            this.updateById(matchUser);
        }

        //查询对方有没有匹配过。
        UserMatch targetMatch = getMatchUser(targetUserId, userId);

        return targetMatch != null && targetMatch.getIsLike() == 1;
    }

    @Override
    public void dislike(Long userId, Long targetUserId) {
        UserMatch matchUser = getMatchUser(userId, targetUserId);
        if (matchUser == null){
            matchUser = new UserMatch();
            matchUser.setIsLike(0);
            matchUser.setMatchUserId(targetUserId);
            matchUser.setUserId(userId);
            this.save(matchUser);
            return;
        }
        matchUser.setIsLike(1);
        this.updateById(matchUser);
    }

    @Override
    public Integer getTodayMatchCount(Long userId) {
        return baseMapper.getTodayMatchCount(userId);
    }

    public UserMatch getMatchUser(Long userId, Long targetUserId){
        LambdaQueryWrapper<UserMatch> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(UserMatch::getUserId, userId)
                .eq(UserMatch::getMatchUserId, targetUserId);
        return this.getOne(wrapper);
    }
}
